<?php

namespace App\Repository\Rebate;

use App\Models\Rebate\RebateModel as Model;
use App\Models\Rebate\RebateRulesModel as RulesModel;
use App\Repository\BaseRepository;

class RebateRepository extends BaseRepository
{
    public $model;
    public $log;

    public function __construct()
    {
        $this->model = new Model();
//    $this->log = new Logger('anchor');
//    $this->log->pushHandler(
//      (new RotatingFileHandler(storage_path('/logs/anchor.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
//    );
        parent::__construct();
    }

    //列表
    public function index($where, $page = 1, $limit = 10)
    {
        $pk = $this->model->getKeyName();

        $data = [];
        $data['typeList'] = $this->model->getTypeList();
        $data['statusList'] = $this->model->getStatusList();

        $this->model = $this->model->searchWhere($where);
//        先要总数
        $totalRows = $this->model->count($pk);
//        再加上分页查询
        $rows = $this->model->page($page, $limit)->with(["rules" => function ($query) {
            $query->select(['rebate_id', 'month', 'money']);
        }, "product" => function ($query) {
            $query->select(['id', 'name']);
        }, "users" => function ($query) {
            $query->select(['id', 'nick_name']);
        }])->get();
        $data['dataList'] = $rows;

        return $this->returnMsg(200, '查询成功', $data, $totalRows);
    }

//   订单返费信息
//    public function details($where, $page = 1, $limit = 10, $loadExtra = 0)
//    {
//        $OrdersModel = new \App\Models\Orders\OrdersModel();
//        $pk = $OrdersModel->getKeyName();
//        $OrdersModel = $OrdersModel->searchWhere($where);
////        先要总数
//        $totalRows = $OrdersModel->whereHas('rebate', function ($query) {
//            $query->select(['id']);
//        })->count($pk);
////        echo $this->getLastSql();
////        再加上分页查询
//        $rows = $OrdersModel->page($page, $limit)->with(["rebate" => function ($query) {
//            $query->select(['id', 'name', 'type', 'status', 'effective_at', 'instantly_money', 'all_money']);
//        }, "ordersUser" => function ($query) {
//            $query->select(['id', 'source_type', 'sell_name', 'pay_name', 'pay_identity', 'pay_phone', 'post_province', 'post_city', 'post_area', 'post_address']);
//        }, "rebateLogs" => function ($query) {
//            $query->select(['id', 'orders_id', 'created_at', 'type', 'month', 'money']);
//        }, "rebateUser" => function ($query) {
//            $query->select(['id', 'nick_name']);
//        }, "reviewUser" => function ($query) {
//            $query->select(['id', 'nick_name']);
//        }])->whereHas('rebate', function ($query) {
//            $query->select(['id']);
//        })->orderBy($pk, 'DESC')->get();
//        $productNameOptions = $rebateNameOptions = [];
//        if ($loadExtra === 1) {
////            获取规则名称与产品名称给前台做为搜索选择内容
//            $opts = $this->model->with(["product" => function ($query) {
//                $query->select(['id', 'name']);
//            }])->select(['id', 'product_id', 'name'])->where(["status" => 0])->get();
////            print_r($opts);
//            if (!empty($opts)) {
//                foreach ($opts as $k => $opt) {
//                    $rebateNameOptions[] = ["id" => $opt['id'], "name" => $opt['name']];
//                    if (!empty($opt['product'])) {
//                        $productNameOptions[] = ["id" => $opt['product']['id'], "name" => $opt['product']['name']];
//                    }
//                }
//            }
//        }
////        把相应的状态信息也一起返过去,就不用再次请求
//        $data = [
//            'dataList' => $rows,
//            'isOnlineStatus' => config('card.isOnlineStatus'),
//            'rebateStatus' => config('card.rebateStatus'),
//            'productNameOptions' => $productNameOptions,
//            'rebateNameOptions' => $rebateNameOptions,
//            'reviewStatus' => config('card.reviewStatus'),
//        ];
//        return $this->returnMsg(200, '查询成功', $data, $totalRows);
//
//    }

//    修改订单的卡的在网状态,在订单表里
    public function changeIsOnline($userId, $ordersId, $value)
    {
        $OrdersModel = new \App\Models\Orders\OrdersModel();
        if (false !== $OrdersModel->where(['id' => $ordersId])->update(['is_online' => $value])) {
//            记录操作日志
            $LogsModel = new \App\Models\LogsModel();
            $valueName = config('card.isOnlineStatus')[$value];
            $LogsModel->saveIt(0, $userId, $ordersId, "修改了卡的在网状态[" . $valueName . "]");
        }
        return $this->returnMsg(200, '操作成功');
    }

//修改卡的余额
    public function changeCardBalance($userId, $ordersId, $value)
    {
        $OrdersModel = new \App\Models\Orders\OrdersModel();
        if (false !== $OrdersModel->where(['id' => $ordersId])->update(['card_balance' => $value])) {
//            记录操作日志
            $LogsModel = new \App\Models\LogsModel();
            $LogsModel->saveIt(0, $userId, $ordersId, "修改了卡的余额为[" . $value . "]");
        }
        return $this->returnMsg(200, '操作成功');
    }

//审核定单
    public function reviewIt($userId, $ordersId, $status, $reason = null)
    {
        $OrdersModel = new \App\Models\Orders\OrdersModel();
        $updata = [
            'review_user_id' => $userId,
            'review_status' => $status,
            'review_at' => date('Y-m-d H:i:s')
        ];
        if (false !== $OrdersModel->where(['id' => $ordersId])->update($updata)) {
//            记录操作日志
            $LogsModel = new \App\Models\LogsModel();
            $statusName = config('card.reviewStatus')[$status];
            $LogsModel->saveIt(0, $userId, $ordersId, "审核了订单，状态为[" . $statusName . "]");
            //            填写了备注原因
            if (!empty($reason)) {

                $ReasonModel = new \App\Models\Orders\OrdersReasonModel();
                $ReasonModel->saveReason($userId, $ordersId, $reason);
            }
        }
        return $this->returnMsg(200, '操作成功');
    }

//审核不通过原因列表
    public function reviewReasonList($orderId)
    {
        $ReasonModel = new \App\Models\Orders\OrdersReasonModel();
        $rows = $ReasonModel->with(["user" => function ($query) {
            $query->select(['id', 'nick_name']);
        }])->where(['orders_id' => $orderId])->select(['users_id', 'created_at', 'content'])->get();
        return $this->returnMsg(200, '操作成功', ['dataList' => $rows]);
    }

//日志列表
    public function logsList($orderId)
    {
        $LogsModel = new \App\Models\LogsModel();
        $rows = $LogsModel->with(["user" => function ($query) {
            $query->select(['id', 'nick_name']);
        }])->where(['type' => 0, 'table_id' => $orderId])->select(['users_id', 'created_at', 'content'])->get();
        return $this->returnMsg(200, '操作成功', ['dataList' => $rows]);
    }

    public function add($request)
    {
        return $this->edit($request);
    }

    public function edit($request)
    {
        if (empty($request)) {
            return $this->returnMsg(2, '操作数据不能为空');
        }
        $rulesFieldMsg = [
            'name' => '规则名字不能为空',
            'product_id' => '产品不能为空'
        ];
        $pk = $this->model->getKeyName();
        $id = 0;
        if ($request->has($pk)) {
            $id = $request->get($pk);
            if ($id <= 0) {
                return $this->returnMsg(2, '修改Id不能为空');
            }
        }
        $optionalFields = $this->model->getTableField();
        $mustField = [];
        if (!empty($rulesFieldMsg) && is_array($rulesFieldMsg)) {
            $mustField = array_keys($rulesFieldMsg);
        }
        $updateData = $this->getRealData($request, $mustField, $optionalFields, $rulesFieldMsg);
        if (!empty($updateData) && is_string($updateData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $updateData
            );
        }
//        规则下的总金额
        $allMoney = 0;
        if (!empty($request->rules)) {
            foreach ($request->rules as $k => $v) {
                $allMoney += floatval($v['money']);
            }
        }
        $updateData['all_money'] = $allMoney;
        if ($id > 0) {
//          修改时不能修改产品
            unset($updateData['product_id']);
            $where = [[$pk, '=', $id]];
            $isTrue = $this->model->where($where)->count($pk);
            if (!$isTrue) {
                return $this->returnMsg(100, '未查询到修改的数据');
            }
//          联合更多规则一起修改
            $res = $this->model->where($where)->update($updateData);
            if (false !== $res) {
                $modelRules = new RulesModel();
//          删除旧的规则数据，然后重新写入
                $modelRules->where(["rebate_id" => $id])->delete();
                if (!empty($request->rules)) {
                    $rules = [];
                    foreach ($request->rules as $k => $v) {
                        $v['rebate_id'] = $id;
                        $rules[] = $v;
                    }
                    $modelRules->insert($rules);
                }
                return $this->returnMsg(200, '修改成功');
            } else {
                return $this->returnMsg(3, '请重新修改' . $this->getLastSql());
            }
        } else {
            // 新增时,同一产品只能有一条规则
            $updateData['admin_users_id'] = $request->user->id;
            $where = [['product_id', '=', $updateData['product_id']], ['status', '=', 0]];
            $isTrue = $this->model->where($where)->count($pk);
            if ($isTrue) {
                return $this->returnMsg(1, '此产品已经存在规则');
            }
            $insertId = $this->model->insertGetId($updateData);
            if ($insertId > 0) {
                if (!empty($request->rules)) {
                    $modelRules = new RulesModel();
                    $rules = [];
                    foreach ($request->rules as $k => $v) {
                        $v['rebate_id'] = $insertId;
                        $rules[] = $v;
                    }
                    $modelRules->insert($rules);
                }
                return $this->returnMsg(200, '添加成功');
            } else {
                return $this->returnMsg(4, '数据新增异常');
            }
        }

    }
}
